#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash elpa-2019.05.001.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar environment-modules

wget -t 40 -c -P $buildpath https://www.cp2k.org/static/downloads/elpa-2019.05.001.tar.gz
tar -xvf $buildpath/elpa-2019.05.001.tar.gz -C $buildpath && rm -rf $buildpath/elpa-2019.05.001.tar.gz
cd $buildpath/elpa-2019.05.001
export CC=`which mpicc`
export CXX=`which mpicxx`
export FC=`which mpifort`
export LDFLAGS="-L$installpath/EXTRA/mathlib"
export CFLAGS="-L$installpath/EXTRA/mathlib"
export CXXFLAGS="-L$installpath/EXTRA/mathlib"
export FCFLAGS="-L$installpath/EXTRA/mathlib"
LIBS="$installpath/EXTRA/mathlib/libscalapack.a $installpath/EXTRA/mathlib/liblapack.a $installpath/EXTRA/mathlib/libblas.a"
./configure --prefix=$installpath/elpa-2019.05.001 --enable-openmp --enable-shared=no --disable-sse --disable-sse-assembly --disable-avx --disable-avx2
make
make install
cat>"$installpath/elpa-2019.05.001/elpa_modulefiles"<<EOF
#%Module1.0
conflict elpa
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set ELPA \$pwd
setenv ELPA \$ELPA
prepend-path LD_LIBRARY_PATH \$ELPA/lib
prepend-path INCLUDE \$ELPA/include
EOF

rm -rf $buildpath/elpa-2019.05.001
